import BScroll from '@better-scroll/core'
import Slide from '@better-scroll/slide'

import { onMounted, onUnmounted, ref, onActivated, onDeactivated } from 'vue'

BScroll.use(Slide)

export default function useSlider (wrapperRef) {
  // 定义slider用于return
  const slider = ref(null)
  // 获取激活的索引
  const currentPageIndex = ref(0)

  // dom渲染后初始化slider
  onMounted(() => {
    // 第一个参数为DOM，因为是ref获取，所以需要.value
    slider.value = new BScroll(wrapperRef.value, {
      click: true,
      scrollX: true, // 横向slide
      scrollY: false,
      momentum: false, // 惯性特效，防止一次滑动滚动多页
      bounce: false,
      probeType: 2, // 能够监听pageIndex变化
      slide: true
    })

    // 监听pageIndex并获取
    slider.value.on('slideWillChange', (page) => {
      currentPageIndex.value = page.pageX
    })
  })

  // 销毁slider
  onUnmounted(() => {
    slider.value.destroy()
  })
  onActivated(() => {
    slider.value.enable()
    slider.value.refresh()
  })
  onDeactivated(() => {
    slider.value.disable()
  })
  return {
    slider,
    currentPageIndex
  }
}
